package org.example.mq.brokerserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.mq.common.Consumer;
import org.example.mq.common.ConsumerEnv;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class MQqueue {
    private String name;
    private boolean durable = false;
    //暂未实现功能
    private boolean exclusive = false;//排他性
    private boolean autoDelete = false;//自动删除
    private Map<String, Object> options = new HashMap<>();
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    //添加一个新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv){
        consumerEnvList.add(consumerEnv);
    }
    public ConsumerEnv chooseConsumer(){
        if(consumerEnvList.size()==0){
            return null;
        }
        //计算要取的元素的下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }
    public String getName() {
        return name;
    }
    public Object getOptions(String key){
        return options.get(key);
    }
    public void setOptions(String key,Object value){
        this.options.put(key,value);
    }
    public String getOptions() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(this.options);
    }
    public void setOptions(String options) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        this.options = objectMapper.readValue(options, new TypeReference<Map<String, Object>>() {
        });
    }
    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public void setOptions(Map<String, Object> options) {
    }

}
